#include "Net_Client.h"

NetClient::NetClient() : IKernelTask( "Net_Client", 20 )
{
	logger << "Constructing object" << std::endl;
}

NetClient::~NetClient()
{
	SDLNet_Quit();

	logger << "Destructing object" << std::endl;
}

GCPtr<NetClient> NetClient::getInstance()
{
	static GCPtr<NetClient> netClient = new NetClient();
	return netClient;
}

bool NetClient::Start()
{
	if( SDLNet_Init() < 0 )
	{
		fprintf( stderr, "SDLNet_Init: %s\n", SDLNet_GetError() );
		system( "Pause" );
		return false;
	}

	// Resolve the host we are connecting to
	if( SDLNet_ResolveHost( &ip, XMLSettings::getInstance().getServerIP(), 2000 ) < 0 )
	{
		fprintf( stderr, "SDL_NetResolveHost: %s\n", SDLNet_GetError() );
		system( "Pause" );
		return false;
	}

	// Open a connection with the ip provided ( listen to the hosts port )
	if( !( sd = SDLNet_TCP_Open( &ip ) ) )
	{
		fprintf( stderr, "SDLNet_TCP_Open: %s\n", SDLNet_GetError() );
		system( "Pause" );
		return false;
	}

	return true;
}

void NetClient::Stop()
{
	SDLNet_TCP_Close( sd );
	logger << "Connection closed" << std::endl;
}

void NetClient::Update()
{

	for each (CoordPacket currentPacket in vPacketQueue)
	{
		if( SDLNet_TCP_Send( sd, ( void* ) &currentPacket, sizeof( CoordPacket ) ) < sizeof( CoordPacket ) )
		{
			fprintf( stderr, "SDLNet_TCP_Send: %s\n", SDLNet_GetError() );
		}
		cout << "Package sent" << endl;
	}
	vPacketQueue.clear();
}

void NetClient::queuePacket( CoordPacket packet )
{
	vPacketQueue.push_back(packet);
}

